package com.meida.student.app.user.handler;

import com.meida.common.base.entity.EntityMap;
import com.meida.common.mybatis.interceptor.PageInterceptor;
import com.meida.common.mybatis.model.PageParams;
import com.meida.common.mybatis.query.CriteriaQuery;
import com.meida.common.security.OpenHelper;
import com.meida.module.bus.client.enums.BalanceLogTypeEnum;
import com.meida.module.bus.provider.service.BusOrderService;
import com.meida.module.pay.client.entity.PayBalance;
import com.meida.module.pay.client.entity.PayBalanceLog;
import com.meida.module.pay.provider.service.PayBalanceLogService;
import com.meida.module.pay.provider.service.PayBalanceService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.math.BigDecimal;
import java.util.List;

/**
 * 余额记录扩展
 */
@Component
public class PayBalanceLogPageListHandler implements PageInterceptor<PayBalanceLog> {

    @Autowired
    private PayBalanceService payBalanceService;

    @Autowired
    private PayBalanceLogService payBalanceLogService;

    @Override
    public void prepare(CriteriaQuery<PayBalanceLog> cq, PageParams pageParams, EntityMap params) {
        Long userId = OpenHelper.getUserId();
        cq.clear();
        cq.select(PayBalanceLog.class, "balanceId", "amount", "title", "body", "logType");
        cq.eq(PayBalanceLog.class, "userId", userId);
    }

    @Override
    public void complete(CriteriaQuery<PayBalanceLog> cq, List<EntityMap> result, EntityMap extra) {
        Long userId = OpenHelper.getUserId();
        PayBalance payBalance = payBalanceService.addUserBalance(userId);
        BigDecimal balanceAmount = payBalance.getAmount();
        extra.put("balanceAmount", balanceAmount);
        for (EntityMap entityMap : result) {
            Integer logType = entityMap.getInt("logType");
            BalanceLogTypeEnum balanceLogTypeEnum = BalanceLogTypeEnum.getByValue(logType);
            entityMap.put("logTypeDesc", balanceLogTypeEnum.getLabel());
        }
        //支出金额
        BigDecimal spendingAmount = payBalanceLogService.totalAmountByLogType(userId, BalanceLogTypeEnum.logType2.getValue());
        extra.put("spendingAmount", spendingAmount);
        //支出金额
        BigDecimal refungAmount = payBalanceLogService.totalAmountByLogType(userId, BalanceLogTypeEnum.logType5.getValue());
        extra.put("refungAmount", refungAmount);
    }
}
